package com.demo.apparel.interceptor;

import com.demo.apparel.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getRequestURI();
        System.out.println("JwtInterceptor拦截路径: " + path);

        // 登录接口放行
        if ("/web/admin/login".equals(path)) {
            System.out.println("登录接口放行");
            return true;

        }

        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || authHeader.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("缺少Authorization头");
            return false;
        }

        // 兼容 Bearer token 和裸 token
        String token;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7); // 去掉 "Bearer "
        } else {
            token = authHeader;
        }

        try {
            if (jwtUtils.isTokenExpired(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("token已过期");
                return false;
            }
            Claims claims = jwtUtils.parseToken(token);
            request.setAttribute("userId", claims.getSubject()); // 保存userId供controller使用
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无效的token");
            return false;
        }
    }
}
